package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.utils.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.SubmitNewsTwoService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class SubmitNewsTwoServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements SubmitNewsTwoService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;


    @Override
    public ResponseResult submitNewsTwo(WmNewsDto wmNewsDto) {
        //参数校验
        if (wmNewsDto == null || wmNewsDto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或者修改文章
            //属性拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
            //封面
        if (wmNewsDto.getImages() != null && wmNewsDto.getImages().size() != 0){
            String images = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(images);
        }
        //自动封面
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //封装调用保存或者修改文章的方法
        saveOrUpdateNews(wmNews);

        //判断是否是要保存为草稿,是就直接结束方法
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿的数据处理
        //要保存文章和素材的关系
        //获取文章中的图片信息
        List<String> materials = ectractUrlInfo(wmNewsDto.getContent());

        //保存文章和数据的关系
        saveRelativeInfoForCover(wmNews,wmNewsDto,materials);

        //调用审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());


        return ResponseResult.okResult(wmNews);
    }

    //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
    private void saveRelativeInfoForCover(WmNews wmNews, WmNewsDto wmNewsDto, List<String> materials) {
        //判断是否为自动
        List<String> images = new ArrayList<>();
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //是自动,根据文章内容中有几张图片来判断封面为几张图
            if (materials.size() >= 3){
                //多图模式
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if(materials.size()>=1 && materials.size() < 3){
                //单图模式
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                String image = materials.get(0);
                images.add(image);
            }else {
                //无图模式
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images!=null && images.size()>0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            this.updateById(wmNews);
        }
        if (images!=null && images.size()>0){
            //保存文章素材关系
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    //保存文章素材关系
    private void saveRelativeInfo(List<String> images, Integer id, Short type) {
        if (images!=null && images.size() > 0){
            //根据url查找素材
            List<WmMaterial> dbwmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            //判断素材是不是有效
            if(dbwmMaterials==null || dbwmMaterials.size() == 0){
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            if(dbwmMaterials.size() != images.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            List<Integer> idList = dbwmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存
            wmNewsMaterialMapper.saveRelations(idList,id,type);

        }
    }

    //获取文章中的 图片信息
    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList();
        if (content!=null){
            List<Map> contentMap = JSON.parseArray(content, Map.class);
            for (Map map : contentMap) {
                if (map.get("type").equals("image")){
                    String imageUrl = (String) map.get("value");
                    list.add(imageUrl);
                }
            }
        }
        return list;
    }

    /**
     * 新增或修改文章
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        //补全数据
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setCreatedTime(new Date());
        wmNews.setStatus((short) 1);

        //通过前端传来数据来确定是添加数据还是修改数据
        if (wmNews.getId() == null){
            //没有id,直接新增
            this.save(wmNews);
        }else {
            //修改数据
            //修改前将文章和素材的关系删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getId,wmNews.getId()));
            this.updateById(wmNews);
        }
    }
}
